var myTemp = '';
var hotFunds = '';
var hotThemFunds = '';
var estimateFunds = '';
var estimateTemp = '';
var myEstimateFunds = [];
var estimateSelf = '';
var  self = '';
define("p_funds", ['m_basepage', 'text!T_UIFundsView', 'text!T_UIHotFundsView','text!T_UIHotThemFundsView', 'text!T_UIEstimateFundsView', 'text!T_UIFundSearchView', "m_tpl", "m_hammer"], function(Basepage, T_UIFundsView, T_UIHotFundsView,T_UIHotThemFundsView, T_UIEstimateFundsView, T_UIFundSearchView) {
    myTemp = T_UIFundsView;
    estimateTemp = T_UIEstimateFundsView;
    var h = Basepage.extend({
        initialize : function() {
            this.page.ad = JSON.parse(localStorage.getItem('homeAd'));
            this.page.viewId = '#p-view-funds', this.page.name = "p_view_funds", this.page.html = '';
            this.page.curModel = null;
            this.page.properity = {
                currentType : -1,
                currentOrder : 2,//默认近半年
            }
            //先将模板填充下去，接着再填充数据
            wapper = $(T_UIFundSearchView);
            this.page.html = wapper;
            this.pageAdd();
            //tab菜单进行初始化
            A.launch({
                showPageLoading : false,
                isAutoRender : true,
                crossDomainHandler : $util.ajax
            });

            setTimeout(function() {
                var fundtab = sessionStorage.getItem("fundtab");
                if (!sessionStorage.getItem('historyBack') && (!fundtab || fundtab == 0 || fundtab == '0' )) {
                    $('#commonList').addClass('uhide');
                    $('#hot-list-funds').removeClass('uhide');
                }
            }, 300);
            //this.page.html.find('#hot-list-funds').append('<div>88888888888888888</div>');
            //  if(false){
            localStorage.removeItem('fundsIndex')    
            if (localStorage.getItem('fundsIndex2')) {
                allFunds = this.page.model = JSON.parse(localStorage.getItem('fundsIndex2'));
                this.page.html = (_.template(T_UIFundsView))({
                    list : this.page.model,
                    pageKey : 'fundsIndex',
                    pageName : this.page.name
                });
                this.page.curModel = this.page.model;
                // wapper = $(T_UIFundSearchView);
                var fundsHtml = (_.template(T_UIFundsView))({
                    list : this.page.model,
                    pageKey : 'fundsIndex',
                    pageName : this.page.name
                });
                $('#list-funds').html(fundsHtml);
                //初始化头部导航栏
                //var  initObj =  initList();
                //获取我的基金
                getMyFund();
                //两个排序按钮点击事件
                // $("#orderBtn2").click(
                // function(){toggleChoose();}
                // );

            }
            // if(!sessionStorage.getItem('historyBack')||!this.page.model||!this.page.curModel){
            // this._renderHTML();
            // }
            localStorage.removeItem('hotFundsIndex')
            if (localStorage.getItem('hotFundsIndex2')) {
                hotFunds = this.page.hotModel = JSON.parse(localStorage.getItem('hotFundsIndex2')).returnlist;
                var  hotAct   = JSON.parse(localStorage.getItem('hotFundsIndex2')).hotAct;
                this.page.hotCurModel = this.page.hotModel;
                var fundsHtml = (_.template(T_UIHotFundsView))({
                    hotAct:hotAct,
                    list : hotFunds,
                    pageKey : 'hotFundsIndex',
                    pageName : this.page.name,
                    ad : this.page.ad
                });
                $('#hot-html').html(fundsHtml);
                //$('#hot-list-funds').html(fundsHtml);
            } else {
                toast();
                //如果本地不存在就弹出加载提示
            }
            localStorage.removeItem('hotThemFundsIndex')
            if (localStorage.getItem('hotThemFundsIndex2')) {
                hotThemFunds = this.page.hotThemModel = JSON.parse(localStorage.getItem('hotThemFundsIndex2'));
                this.page.hotThemCurModel = this.page.hotThemModel;
                 hotThemFunds =this.page.hotThemModel;
                var fundsHtml = (_.template(T_UIHotThemFundsView))({
                    fundList : hotThemFunds,
                    pageKey : 'hotThemFundsIndex',
                });
                $('#hot-them-html').html(fundsHtml);
            } 
            localStorage.removeItem('estimateFundsIndex')
            //净值估算基金缓存
            if (localStorage.getItem('estimateFundsIndex2')) {
                estimateFunds = this.page.estimateModel = JSON.parse(localStorage.getItem('estimateFundsIndex2'));
                this.page.estimateCurModel = this.page.estimateModel;
                var fundsHtml = (_.template(T_UIEstimateFundsView))({
                    list : estimateFunds,
                    pageKey : 'estimateFundsIndex',
                    pageName : this.page.name
                });
                $('#estimate-list-funds').html(fundsHtml);
            } else {
                toast();
                //如果本地不存在就弹出加载提示
            }

            if (!sessionStorage.getItem('historyBack') || !this.page.model || !this.page.curModel) {
                this._renderHTML();
            } else {
                setTimeout(function() {
                    var fundtab = sessionStorage.getItem("fundtab");
                    if (fundtab && (fundtab == 1 || fundtab == '1' )) {
                        tabClick(fundtab);
                    }
                }, 300);

                sessionStorage.removeItem('historyBack');
            }
            //初始并绑定相关事件
            this.bindMethod();
            if (!sessionStorage.getItem('historyBack') || !this.page.model || !this.page.curModel) {
                this._renderHotHTML();
                this._renderHotThemHTML();
            } else {
                sessionStorage.removeItem('historyBack');
            }
            //获取估算净值
            if (!sessionStorage.getItem('historyBack') || !this.page.model || !this.page.curModel) {
                this._renderEstimateHTML();
            } else {
                sessionStorage.removeItem('historyBack');
            }
            //getCouponData();
        },
        enter : function() {
        },
        back : function() {
        },
        leave : function() {
        },
        _renderEstimateHTML : function() {
             estimateSelf = this;
            //修正引用对象
            var param = {
                'function' : 'NF083'
            };
            toast();
            nfApp._ajax(param, function(json) {
                closeToast();
                if (json.code == SUCCESS_FLAG) {
                    closeToast();
                    if (json.datas.length > 0) {
                        estimateSelf.page.estimateModel = json.datas;
                        estimateSelf.page.estimateCurModel = json.datas;
                        currentEstimateFunds =json.datas;
                        setLocVal("estimateFundsIndex2", json2str(json.datas));
                        estimateFunds = json.datas;
                        var fundsHtml = (_.template(T_UIEstimateFundsView))({
                            list : estimateSelf.page.estimateModel,
                            pageKey : 'estimateFundsIndex',
                            pageName : estimateSelf.page.name
                        });
                        // wapper = $(T_UIFundSearchView);
                        $('#estimate-list-funds').html(fundsHtml);
                        // self.init();
                        //初始并绑定相关事件
                        estimateSelf.bindMethod();
                        if (myFunds.length > 0 && estimateFunds.length > 0) {
                            //将我关注的含有净值估算的显示出来
                            selectMyEstimateFunds();
                        }
                    }
                } else {
                    $toast(json.message);
                }
                setTimeout(function() {
                    var fundtab = sessionStorage.getItem("fundtab");
                    if (fundtab && (fundtab == 2 || fundtab == '2')) {
                        tabClick(fundtab);
                    }
                }, 300);
            });

        },_renderHotThemHTML : function() {
            var hotThemSelf = this;
            //修正引用对象
            var param = {
                'function' : 'NF123'
            };
            if (islogin()) {
                param = $.extend(param, {
                    "eqcustno" : localStorage.getItem("eqcustno"),
                    "datasource" : "DC",
                    "noticeid" : getLocVal("noticeid"),
                    "fundapiflag" : "0"
                });
            }
            //toast();

            nfApp._ajax(param, function(data) {
                //console.log(data);
                fundList  = data.tagList;
                closeToast();
                if (data.code == SUCCESS_FLAG) {
                     hotThemSelf.page.hotThemModel = fundList;
                        hotThemFunds =fundList;
                    var fundsHtml = (_.template(T_UIHotThemFundsView))({
                        fundList:fundList,
                        pageKey:'hotThemFundsIndex'
                    });
                    setLocVal('hotThemFundsIndex2',json2str(fundList));
                    $('#hot-them-html').html(fundsHtml);
                }else{//异常
                     setTimeout("nfApp.toastBox('0',\'"+data.message+"\')",1000);
                     
                }
                getCouponData();
            });

        },
        _renderHotHTML : function() {
            var hotSelf = this;
            //修正引用对象
            var param = {
                'function' : 'NF038'
            };
            if (islogin()) {
                param = $.extend(param, {
                    "eqcustno" : localStorage.getItem("eqcustno"),
                    "datasource" : "DC",
                    "noticeid" : getLocVal("noticeid"),
                    "fundapiflag" : "0"
                });
            }
            toast();

            nfApp._ajax(param, function(json) {
                closeToast();
                if (json.code == SUCCESS_FLAG) {
                    closeToast();
                    if (json.returnlist.length > 0) {
                        hotSelf.page.hotModel = json.returnlist;
                        hotSelf.page.hotCurModel = json.returnlist;
                        setLocVal("hotFundsIndex2", json2str(json));
                        

                        
                        hotFunds = json.returnlist;
                        hotSelf.page.ad = json.ad;
                        localStorage.setItem('homeAd', JSON.stringify(json.ad));
                        var fundsHtml = (_.template(T_UIHotFundsView))({
                            hotAct:json.hotAct,
                            list : hotSelf.page.hotModel,
                            pageKey : 'hotFundsIndex',
                            pageName : hotSelf.page.name,
                            ad : hotSelf.page.ad
                        });
                        $('#hot-html').html(fundsHtml);
                        // wapper = $(T_UIFundSearchView);
                       // $('#hot-list-funds').html(fundsHtml);
                        // self.init();
                        //初始并绑定相关事件
                        hotSelf.bindMethod();

                    }
                } else {
                    $toast(json.message);
                }
            });

        },
        _renderHTML : function() {
             self = this;
            //修正引用对象
            var param = {
                "function" : "NF017",
                "async" : false,
                //"lastupdatetime":(parseInt(localStorage.getItem("utime"))-3600*24*30),}
                "lastupdatetime" : localStorage.getItem("utime2"),
            }
            if (islogin()) {
                param = $.extend(param, {
                    "eqcustno" : localStorage.getItem("eqcustno"),
                    "datasource" : "DC",
                    // "sessionkey" : localStorage.getItem("sessionkey"),
                    "fundapiflag" : "0"
                });
            }
            toast();
            nfApp._ajax(param, function(json) {

                if (json.code == SUCCESS_FLAG) {
                    closeToast();
                    if (json.returnlist.length > 0) {
                        localStorage.setItem("utime2", json.utime);
                        self.page.model = json.returnlist;
                        allFunds = json.returnlist;
                        self.page.curModel = json.returnlist;
                        currentFunds = json.returnlist;
                        localStorage.setItem('fundsIndex2', JSON.stringify(self.page.model));
                        var fundsHtml = (_.template(T_UIFundsView))({
                            list : self.page.model,
                            pageKey : 'fundsIndex',
                            pageName : self.page.name
                        });
                        $('#list-funds').html(fundsHtml);
                        //初始并绑定相关事件
                        self.bindMethod();
                    } else {
                        self.bindMethod();
                    }

                    //初始化头部导航栏
                    //   var  initObj =  initList();
                    //获取我的基金
                    getMyFund();
                } else {
                    $toast(json.message);
                }
                setTimeout(function() {
                    var fundtab = sessionStorage.getItem("fundtab");
                    if (fundtab && (fundtab == 1 || fundtab == '1' )) {
                        tabClick(fundtab);
                    }
                }, 300);
            });
        },
        test : function() {

        },
        bindMethod : function() {//绑定事件集合
             self = this,
                a = this.jdom,
                hotSelf = this,
                estimateSelf = this;
                hotThemSelf = this;
                var  filterFlag  = false;
            a.delegate('.js-themFund', "click", function(e) {
                if (event != undefined) {
                    event.stopPropagation();
                }
                var  index  = $(this).data('index');
                 var fundDetail = hotThemFunds[index];
                var  descUrl = '';
                descUrl = hotThemFunds[index].descUrl;
                if(descUrl){
                 location.href  = descUrl;
                    }else{
                        location.href = "fundDetail.html?v=20180614&" + paramSerialize(fundDetail);
                    }
            }),a.delegate('.js-ztMore', "click", function(e) {
               location.href  = 'wealth/themChooseFund.html';
            }),a.delegate('.js-more', "click", function(e) {
                tabClick(1);
            }),a.delegate('#moneyClass>div', "click", function(e) {
                var  index = $(this).data('index');
                 if( $(this).hasClass('classTabActive') ){
                     return;
                 }else{
                     $('#moneyClass>div').removeClass('classTabActive');
                     $('#moneyClass>div').eq(index).addClass('classTabActive');
                    // var  fun  = 'tabListClick(7,'+ index+')';
                    //ueppscript('fundProduct','content',fun);
                     var res = classifyFunds(currentType, "", allFunds, $(this).data('index') );
                      self.page.curModel = res;
                        $('#list-funds').html((_.template(myTemp))({
                            list : res,
                            currentInscTab : currentInscTab
                        }));
                    
                 }
            }),a.delegate('#expClass>div', "click", function(e) {
                 var  index = $(this).data('index');
                 if( $(this).hasClass('classTabActive') ){
                     return;
                 }else{
                     $('#expClass>div').removeClass('classTabActive');
                     $('#expClass>div').eq(index).addClass('classTabActive');
                      var res = classifyFunds(currentType, "", allFunds, $(this).data('index') );
                       self.page.curModel = res;
                        $('#list-funds').html((_.template(myTemp))({
                            list : res,
                            currentInscTab : currentInscTab
                        }));
                 }
            }),a.delegate('.js-rank', "click touchstart", function(e) {
                if (event != undefined) {
                    event.stopPropagation();
                }
                // if(sessionStorage.getItem("rankLock")==1){
                    // return;
                // }
                //sessionStorage.setItem("rankLock",1)
                try{
                    var index = $(this).data('index');
                    var rankFlag = '';
                    if (index == '1') {
                        // setLocVal('rankFlag','rxRank');
                        piwikTrackEvent(Piwik_Event_Quota.fund.category,Piwik_Event_Quota.fund.hot_sale.action,"");    
                        rankFlag = 'rxRank';
                         setTimeout(function() {
                            sessionStorage.setItem("rankLock",0);
                        }, 100);
                        window.location.href = 'fundRank.html?rankFlag=' + rankFlag;
                    }
                    if (index == '2') {
                        // setLocVal('rankFlag','dtRank');
                        piwikTrackEvent(Piwik_Event_Quota.fund.category,Piwik_Event_Quota.fund.fixinvest_sale.action,"");    
                        //rankFlag = 'dtRank';
                        window.location.href = 'wealth/themChooseFund.html';
                    }
                    if (index == '3') { 
                         if (localStorage.getItem('originalString') == 'DCVALID' || localStorage.getItem('custType') == 'W') {
                                dialogConfirm('您尚未实名认证，不能进行此操作，是否立即实名认证？','实名认证','authenImme.html');
                                return;
                            }
                        //  setLocVal('rankFlag','syRank');
                        piwikTrackEvent(Piwik_Event_Quota.fund.category,Piwik_Event_Quota.fund.profit_sale.action,"");    
                      //  rankFlag = 'syRank';
                       location.href='cleverInvest/investArea.html';
                    }
    
                    if (index == '4') {
                        // tabClick(1,1);
                        var res = classifyFunds('-2', $.trim($('#search-condition').val()), allFunds);
                        self.page.curModel = res;
                        tabClick(1, 1);
                        piwikTrackEvent(Piwik_Event_Quota.fund.category,Piwik_Event_Quota.fund.fav.action,"");    
                        setTimeout(function() {
                            sessionStorage.setItem("rankLock",0);
                        }, 100);
                        return;
                    }               
                }catch(e){                        
                    } 
                setTimeout(function() {
                    sessionStorage.setItem("rankLock",0);
                }, 100);    
                


            }), a.delegate('.estimateFundsItem', "click", function(e) {
                if (event != undefined) {
                    event.stopPropagation();
                }
                var _param = ( $(this).data('param')).split(',');
                //var fundDetail = estimateSelf.page.estimateCurModel[parseInt(_param[0])];
                var fundDetail =currentEstimateFunds[parseInt(_param[0])];
                setLocVal('fundDetail', JSON.stringify(fundDetail));
                if(sessionStorage.getItem("fundPiwikLock")!=1){
                        sessionStorage.setItem("fundPiwikLock",1);
                        piwikTrackEvent(Piwik_Event_Quota.fund.category,Piwik_Event_Quota.fund.est_market.action,fundDetail.fundcode);
                        setTimeout(function() {
                            sessionStorage.setItem("fundPiwikLock",0);
                        }, 300);                        
                    } 
                //设置是由净值估算跳转过去的,直接显示净值估算
                setLocVal('showEstimate', 'true');
                if (fundDetail.fundcode === superXjbCode) {
                    location.href = 'xjbDetail.html';
                    return;
                }
                var param = {
                    fundcode : fundDetail.fundcode,
                    fundname : fundDetail.fundname,
                    fundtype : fundDetail.fundtype,
                    fundstate : fundDetail.fundstate,
                    fixFundFlag : fundDetail.fixFundFlag,
                     fundrisklevel: fundDetail.fundrisklevel,
                    detailLinkAdd : true,
                    spflag:fundDetail.spflag
                }
                location.href = "fundDetail.html?v=20180614&" + paramSerialize(param);
            }), a.delegate('.hotFundsItem', "click", function(e) {
                if (event != undefined) {
                    event.stopPropagation();
                }
                //设置进入详情的时候不显示估算净值
                setLocVal('showEstimate', 'false');
                if ($(e.target).hasClass('hot-btn-buy'))
                    return;

                //修复点击购买导致冒泡bug
                var _param = ( $(this).data('param')).split(',');
                var fundDetail = hotSelf.page.hotCurModel[parseInt(_param[0])];
                if(sessionStorage.getItem("fundPiwikLock")!=1){
                    sessionStorage.setItem("fundPiwikLock",1);
                    piwikTrackEvent(Piwik_Event_Quota.fund.category,Piwik_Event_Quota.fund.hot_sale_detail.action,fundDetail.fundcode);
                    setTimeout(function() {
                        sessionStorage.setItem("fundPiwikLock",0);
                    }, 300);                        
                }   
                setLocVal('fundDetail', JSON.stringify(fundDetail));    
                if (fundDetail.fundcode === superXjbCode) {
                    location.href = 'xjbDetail.html';
                    return;
                }
                var param = {
                    fundcode : fundDetail.fundcode,
                    fundname : fundDetail.fundname,
                    fundtype : fundDetail.fundtype,
                    fundstate : fundDetail.fundstate,
                    fixFundFlag : fundDetail.fixFundFlag,
                     fundrisklevel: fundDetail.fundrisklevel,
                     spflag:fundDetail.spflag,
                    detailLinkAdd : true
                }
                location.href = "fundDetail.html?v=20180614&" + paramSerialize(param);
            }), a.delegate(".investment", "click", function(e) {//0折定投
                if (event != undefined) {
                    event.stopPropagation();
                }
                var $parent = $(this).parents('.hotFundsItem');
                var _param = ($parent.data('param')).split(',');
                var param = hotSelf.page.hotCurModel[parseInt(_param[0])];
                param = $.extend(param, {
                    'detailLinkAdd' : true
                });

                var fundtype = param.fundtype;
                var spflag = $parent.data('spflag');
                if (param.fixFundFlag) {//申购状态判断
                    if (iswechat() && !checkLock('2', paramSerialize(param))) {//微信登录增加手势密码验证
                        return;
                        // setLocVal('isBuyFlag','1');
                        // setLocVal('buyParam',paramSerialize(param));
                        // window.location.href = "H5lock.html";
                    }
                    if (islogin()) {
                        if (localStorage.getItem('originalString') == 'DCVALID' || localStorage.getItem('custType') == 'W') {
                            dialogConfirm('您尚未实名认证，不能进行此操作，是否立即实名认证？', '实名认证', 'authenImme.html');
                            return;
                        }
                        if (fundtype != "2") {//货币型基金购买不需要判断风险等级
                             if (getLocVal("canBuy") == 'false') {
                                showRiskMessage();
                                return;
                            }
                        }
                        if (getLocVal('infoflag') != 1) {//信息不完整，购买任何基金前都要先补充完整
                            window.location.href = "account/fillMes.html";
                            return;
                        }
                        if(sessionStorage.getItem("fundPiwikLock")!=1){
                            sessionStorage.setItem("fundPiwikLock",1);
                            piwikTrackEvent(Piwik_Event_Quota.fund.category,Piwik_Event_Quota.fund.discount_fixinvest.action,param.fundcode);
                            setTimeout(function() {
                                sessionStorage.setItem("fundPiwikLock",0);
                            }, 300);                        
                        }                         
                        if (spflag == '1') {
                            location.href = 'cleverInvest/indexInvest.html?' + paramSerialize(param);
                        } else {
                            location.href = 'investment.html?' + paramSerialize(param);
                        }

                    } else {

                        if (spflag == '1') {
                            var _url = 'login.html?autoHref=cleverInvest/indexInvest.html&' + paramSerialize(param);
                        } else {
                            var _url = 'login.html?autoHref=investment.html&' + paramSerialize(param);
                        }
                        judgeJumpReloginUrl(_url);
                    }
                }
            }), a.delegate(".hot-btn-buy", "click", function(e) {
                var $parent = $(this).parents('.hotFundsItem');

                var _param = ($parent.data('param')).split(',');
                var fundDetail = hotSelf.page.hotCurModel[parseInt(_param[0])];
                var fundtype = fundDetail.fundtype;
                if (localStorage.getItem('originalString') == 'DCVALID' || localStorage.getItem('custType') == 'W') {
                    dialogConfirm('您尚未实名认证，不能进行此操作，是否立即实名认证？', '实名认证', 'authenImme.html');
                    return;
                }
                if (fundtype != "2") {//货币型基金购买不需要判断风险等级
                     if (getLocVal("canBuy") == 'false') {
                        showRiskMessage();
                        return;
                    }
                }
                if (getLocVal('infoflag') != 1) {//信息不完整，购买任何基金前都要先补充完整
                    window.location.href = "account/fillMes.html";
                    return;
                }
                var param = {
                    fundname : fundDetail.fundname,
                    fundcode : fundDetail.fundcode,
                    fundstate : fundDetail.fundstate,
                    fundtype : fundDetail.fundtype,
                }
                if (iswechat() && !checkLock('1', paramSerialize(param))) {//微信登录增加手势密码验证
                    return;
                    // setLocVal('isBuyFlag','1');
                    // setLocVal('buyParam',paramSerialize(param));
                    // window.location.href = "H5lock.html";
                }
                if (!islogin()) {
                    judgeJumpReloginUrl("login.html?autoHref=subscribe.html&" + paramSerialize(param));
                } else {
                    if (localStorage.getItem('originalString') == 'DCVALID' || localStorage.getItem('custType') == 'W') {//直销客户
                        dialogConfirm('您尚未实名认证，不能进行此操作，是否立即实名认证？', '实名认证', 'authenImme.html');
                    } else {
                        if(sessionStorage.getItem("fundPiwikLock")!=1){
                            sessionStorage.setItem("fundPiwikLock",1);
                            piwikTrackEvent(Piwik_Event_Quota.fund.category,Piwik_Event_Quota.fund.discount_buy.action,fundDetail.fundcode);    
                            setTimeout(function() {
                                sessionStorage.setItem("fundPiwikLock",0);
                            }, 300);                        
                        }                        
                        if (fundDetail.fundcode === superXjbCode) {
                            location.href = 'storage.html';
                            return;
                        }                        
                        window.location.href = "subscribe.html?" + paramSerialize(param);
                    }
                }
            }), a.delegate('.fundsItem', "click", function(e) {
                //进入时候不显示估算净值
                setLocVal('showEstimate', 'false');
                if ($(e.target).hasClass('btn-buy'))
                    return;
                //修复点击购买导致冒泡bug
                var _param = ( $(this).data('param')).split(',');
                //var fundDetail = self.page.curModel[parseInt(_param[0])];
               var fundDetail =  currentFunds[parseInt(_param[0])];
                setLocVal('fundDetail', JSON.stringify(fundDetail));

                if(sessionStorage.getItem("fundPiwikLock")!=1){
                    sessionStorage.setItem("fundPiwikLock",1);
                    piwikTrackEvent(Piwik_Event_Quota.fund.category,Piwik_Event_Quota.fund.view_all.action,fundDetail.fundcode);
                    setTimeout(function() {
                        sessionStorage.setItem("fundPiwikLock",0);
                    }, 300);                        
                }                 
                if (fundDetail.fundcode === superXjbCode) {
                    location.href = 'xjbDetail.html';
                    return;
                }                
                var param = {
                    fundcode : fundDetail.fundcode,
                    fundname : fundDetail.fundname,
                    fundtype : fundDetail.fundtype,
                    fundstate : fundDetail.fundstate,
                    fixFundFlag : fundDetail.fixFundFlag,
                    fundrisklevel: fundDetail.fundrisklevel,
                    detailLinkAdd : true,
                    spflag:fundDetail.spflag
                }
                location.href = "fundDetail.html?v=20180614&" + paramSerialize(param)
            }), a.delegate(".btn-buy", "click", function(e) {//现金宝列表
                var $parent = $(this).parents('.fundsItem');
                var _param = ($parent.data('param')).split(',');
                var fundDetail = self.page.curModel[parseInt(_param[0])];
                var fundtype = fundDetail.fundtype;
                if (localStorage.getItem('originalString') == 'DCVALID' || localStorage.getItem('custType') == 'W') {
                    dialogConfirm('您尚未实名认证，不能进行此操作，是否立即实名认证？', '实名认证', 'authenImme.html');
                    return;
                }
                if (fundtype != "2"||(fundtype=="2"&&getLocVal('moneyRiskLimit')==1)) {//货币型基金购买不需要判断风险等级
                    // if (!judgeRisk()) {
                        // return false;
                    // }
                     if (getLocVal("canBuy") == 'false') {
                                showRiskMessage();
                                return;
                            }
                }
                if (getLocVal('infoflag') != 1) {//信息不完整，购买任何基金前都要先补充完整
                    window.location.href = "account/fillMes.html";
                    return;
                }
                var param = {
                    fundname : fundDetail.fundname,
                    fundcode : fundDetail.fundcode,
                    fundstate : fundDetail.fundstate,
                    fundtype : fundDetail.fundtype,
                }
                if (iswechat() && !checkLock('1', paramSerialize(param))) {//微信登录增加手势密码验证
                    return;
                    // setLocVal('isBuyFlag','1');
                    // setLocVal('buyParam',paramSerialize(param));
                    // window.location.href = "H5lock.html";
                }
                if (!islogin()) {
                    judgeJumpReloginUrl("login.html?autoHref=subscribe.html&" + paramSerialize(param));
                } else {
                    if (localStorage.getItem('originalString') == 'DCVALID' || localStorage.getItem('custType') == 'W') {//直销客户
                        dialogConfirm('您尚未实名认证，不能进行此操作，是否立即实名认证？', '实名认证', 'authenImme.html');
                    } else {
                        if (fundDetail.fundcode === superXjbCode) {
                            location.href = 'storage.html';
                            return;
                        }
                        window.location.href = "subscribe.html?" + paramSerialize(param);
                    }
                }
            }), a.delegate(".selectType", "click", function() {//类型+排序选择列表显示
                showType($(this).data('type'))
            }), a.delegate("#search-condition", "input", function() {//类型选择 过滤
                if (!$.trim($(this).val()))
                    return;
                var res = classifyFunds(self.page.properity.currentType, $.trim($(this).val()), self.page.model);
                //不能缩小搜索范围,删除时无法搜索
                self.page.curModel = res;
                $('#list-funds').html((_.template(T_UIFundsView))({
                    list : res
                }));
                //更新list-funds
            }), a.delegate(".js-total-tab", "click", function() {//类型选择 过滤
                totalTabClick( this );
                 return;
                if($(this).data('type') == 7){//货币型基金分类显示tab
                   $('#moneyClass').parent().removeClass('uhide');
                   $('#expClass').parent().addClass('uhide');
               }else if($(this).data('type') == 6){//指数型基金分类显示tab
                   $('#moneyClass').parent().addClass('uhide');
                   $('#expClass').parent().removeClass('uhide');
               }else{
                    $('#moneyClass').parent().addClass('uhide');
                   $('#expClass').parent().addClass('uhide');
               }
                
                if (currentType != $(this).data('type')) {
                    if($(this).data('init')  ){
                         var res = classifyFunds($(this).data('type'), $.trim($('#search-condition').val()), self.page.model,$(this).data('classType'));
                        // var  fun  = 'tabListClick('+ $(this).data('type')+',"",'+$(this).data('classType')+')';
                         //默认显示第第一类
                          $('#moneyClass >div').removeClass('classTabActive');
                          $('#moneyClass >div').eq(0).addClass('classTabActive');
                          
                          $('#expClass >div').removeClass('classTabActive');
                          $('#expClass >div').eq(0).addClass('classTabActive');
                    }else{
                         var res = classifyFunds($(this).data('type'), $.trim($('#search-condition').val()), self.page.model);
                    }
                   
                    self.page.curModel = res;
                    $('#list-funds').html((_.template(T_UIFundsView))({
                        list : res
                    }));
                    //更新list-funds
                    document.body.scrollTop = 0;
                };
                currentType = $(this).data('type');
            }), a.delegate(".js-est-tab", "click", function() {//类型选择 过滤
                estTabClick(this);
                return;
                if (currentType != $(this).data('type')) {
                    var res = classifyEstimateFunds($(this).data('type'), $.trim($('#search-condition').val()), estimateSelf.page.estimateModel);
                    self.page.estimateCurModel = res;
                    $('#estimate-list-funds').html((_.template(T_UIEstimateFundsView))({
                        list : res
                    }));
                    //更新list-funds
                    document.body.scrollTop = 0;
                };
                currentType = $(this).data('type');
            }), a.delegate(".sortKey-type", "click", function() {//类型选择 过滤
                var currentOrder = self.page.properity.currentOrder
                if (currentOrder != $(this).data('type')) {
                    self.page.properity.currentOrder = $(this).data('type');
                    $('.sortKey-type-active').removeClass('sortKey-type-active');
                    $(this).addClass('sortKey-type-active');
                    currentOrderBy = 1;
                    //切换之后默认高到低
                } else {//反序
                    currentOrderBy = 0 - currentOrderBy;
                    //取反 var orerRes = orderFunds(res,currentOrder);//方向排序
                }
                (currentOrderBy == -1) ? $('.selectType').eq(1).removeClass('order-bottom').addClass('order-top') : $('.selectType').eq(1).removeClass('order-top').addClass('order-bottom');
                if ($(this).data('type') >= 2) {
                    currentInscTab = $(this).data('type') - 2;
                    //修改显示近半年、近一年、今年以来
                }
                var res = classifyFunds(self.page.properity.currentType, $.trim($('#search-condition').val()), self.page.model);
                //针对当前搜索结果进行排序
                var orerRes = orderFunds(res, $(this).data('type'));
                //新排序
                self.page.curModel = orerRes;
                $('#list-funds').html((_.template(T_UIFundsView))({
                    list : orerRes
                }));
                //更新list-funds
                showType('sortKeys-type');
                //隐藏
                $('.selectType').eq(1).text($(this).text().replace(/\s/g, ''))
            });
            

        }
    });
    new h
});
   function estTabClick(obj){
       if (currentType != $(obj).data('type')) {
                    var res = classifyEstimateFunds($(obj).data('type'), $.trim($('#search-condition').val()), estimateSelf.page.estimateModel);
                    self.page.estimateCurModel = res;
                    if(res &&  res.length){
                        $('#estimate-list-funds').html((_.template(estimateTemp))({
                            list : res
                        }));
                    }
                    //更新list-funds
                    document.body.scrollTop = 0;
                };
                currentType = $(obj).data('type');
   }

  function  totalTabClick(obj){
      if($(obj).data('type') == 7){//货币型基金分类显示tab
                   $('#moneyClass').parent().removeClass('uhide');
                   $('#expClass').parent().addClass('uhide');
               }else if($(obj).data('type') == 6){//指数型基金分类显示tab
                   $('#moneyClass').parent().addClass('uhide');
                   $('#expClass').parent().removeClass('uhide');
               }else{
                    $('#moneyClass').parent().addClass('uhide');
                   $('#expClass').parent().addClass('uhide');
               }
                
                if (currentType != $(obj).data('type')) {
                    if($(obj).data('init')  ){
                         var res = classifyFunds($(obj).data('type'), $.trim($('#search-condition').val()), self.page.model,$(obj).data('classType'));
                        // var  fun  = 'tabListClick('+ $(obj).data('type')+',"",'+$(obj).data('classType')+')';
                         //默认显示第第一类
                          $('#moneyClass >div').removeClass('classTabActive');
                          $('#moneyClass >div').eq(0).addClass('classTabActive');
                          
                          $('#expClass >div').removeClass('classTabActive');
                          $('#expClass >div').eq(0).addClass('classTabActive');
                    }else{
                         var res = classifyFunds($(obj).data('type'), $.trim($('#search-condition').val()), self.page.model);
                    }
                    self.page.curModel = res;
                    $('#list-funds').html((_.template(myTemp))({
                        list : res
                    }));
                    //更新list-funds
                    document.body.scrollTop = 0;
                };
                currentType = $(obj).data('type');
  }




var myFunds = '';
//用于保存获取到的我关注的基金
var currentType = -1;
//获取我关注的基金
function getMyFund() {
    var j = {
        'function' : 'NF023'
        //'uuid' : getLocVal(CKEY_DEVICEINFO+'.devicetoken')
    };
    if (islogin()) {
        j = $.extend(j, {
            'lognumber' : Decrypt(sessionStorage.getItem("idno")),
            'certificatetype' : getLocVal('idtype'),
            'accountId' : sessionStorage.getItem('accountId')
        });
    }
    j = $.extend(j, {
        "userid" : sessionStorage.getItem("idno") ? Decrypt(sessionStorage.getItem("idno")) : ""
    });
    nfApp._ajax(j, function(data) {
        if (data.code == SUCCESS_FLAG) {
            myFunds = data.returnlist;
            saveMyConcernFund();
            closeToast();
            if (myFunds.length > 0 && estimateFunds.length > 0) {
                //将我关注的含有净值估算的显示出来
                selectMyEstimateFunds();
            }
        } else {
            $toast(data.message, 2000);
        }
    }, 'json', function() {
        closeToast();
        getAjaxError(arguments[1]);
    }, timeout);
}

//保存我的关注的基金代码，为了在搜索页面能进行对比
function saveMyConcernFund() {
    var myConcernFund = {};
    if (!myFunds.length) {
        clearLocVal('myConcernFund');
    } else {
        for (var i = 0; i < myFunds.length; i++) {
            myConcernFund['fundcode' + myFunds[i].fundcode] = myFunds[i].fundcode;
        }
        setLocVal('myConcernFund', JSON.stringify(myConcernFund));

    }

}

var showType = (function() {
    var curView = '';
    //当前显示
    return function(type) {
        if (curView == type) {
            $('#trangle-tip').removeClass('ub').addClass('uhide');
            $('#' + curView).css('height', '0');
            curView = '';
            return;
        } else if (!curView) {//直接显示
            $('#trangle-tip').add('ub').removeClass('uhide');
            if (type != 'funds-type') {
                $('#trangle-tip').removeClass(' trangle-l').addClass('ub trangle-r ub-pe');
            } else {
                $('#trangle-tip').removeClass('ub trangle-r ub-pe').addClass('trangle-l');
            }
            var h = $('#' + type).find('div').offset().height * (type == 'funds-type' ? 2 : 1);
            $('#' + type).css('transition', 'height 0.25s').css('height', h + 'px');
        } else {//类型选择和排序选择切换
            var hideId = type == 'funds-type' ? '#sortKeys-type' : '#funds-type';
            $(hideId).css('transition', 'none').css('height', '0px');
            if (type == 'funds-type') {
                $('#trangle-tip').removeClass('trangle-r ub-pe').addClass(' trangle-l');
            } else {
                $('#trangle-tip').removeClass(' trangle-l').addClass('ub trangle-r ub-pe');
            }
            var h = $('#' + type).find('div').offset().height * (type == 'funds-type' ? 2 : 1);
            $('#' + type).css('transition', 'height 0.25s').css('height', h + 'px');

        }
        curView = type;
    }
})()

//对头部进行变化
// $('.virtualTitle').css({display:'none !important'});
// $('.virtualTitle[page="p_view_funds"]').css({display:''});
//产品页面中的头部要单独出来显示，无论是微信还是非微信都要显示
var e = document.getElementsByTagName("header")[0].getElementsByTagName("style")[0];
e.innerHTML = 'header{display: -webkit-box !important;display: box !important;}#wrapper{padding-top:2.5em;}#content{padding-top:2.5em;}';
//document.getElementsByTagName("header")[0].appendChild(e)

var currentInscTab = 0;
 var subtype = 0;
function classifyFunds(currentType, searchTxt, data,classType) {//classType只是针对货币基金和指数基金进行的分类操作
 subtype = classType?classType:0;
    datatype = currentType;
    currentFunds = [];
    if (currentType == -2) {//如果是-2则点击的是我的关注
        orderMyFunds();
        //单独出来对我关注的基金先进行排序
        currentFunds = myFunds;
    } else if (currentType != -1 || searchTxt != "") {
        for (var i = 0; i < allFunds.length; i++) {
            if (currentType == -1 || (allFunds[i].QDII && currentType == 99) || (allFunds[i].QDII == false && allFunds[i].investmentstyle == currentType)) {
                if (searchTxt != "") {
                    if (allFunds[i].fundname.indexOf(searchTxt.toUpperCase()) < 0 && allFunds[i].fundcode.indexOf(searchTxt) < 0 && allFunds[i].backfundcode.indexOf(searchTxt) < 0) {
                        continue;
                    }
                }
                if( showCanBuy ){//如果有开启可购买筛选
                          if(parseInt(allFunds[i].fundstate) == 1 || parseInt(allFunds[i].fundstate) == 0  || parseInt(allFunds[i].fundstate) == 6){
                              if(currentType == 7){//货币基金                           
                                    if( allFunds[i].mtype == subtype ){
                                         currentFunds.push(allFunds[i]);
                                    }
                               }else if(currentType == 6){//指数基金
                                    if( allFunds[i].ctype == subtype){
                                         currentFunds.push(allFunds[i]);
                                    }
                               }else{
                                    currentFunds.push(allFunds[i]);
                               }  
                          }
                 }else{
                    if(currentType == 7){//货币基金                           
                        if( allFunds[i].mtype == subtype ){
                             currentFunds.push(allFunds[i]);
                        }
                   }else if(currentType == 6){//指数基金
                        if( allFunds[i].ctype == subtype){
                             currentFunds.push(allFunds[i]);
                        }
                   }else{
                        currentFunds.push(allFunds[i]);
                   }   
                }
            }
            
        }
        
    } else {
       if( showCanBuy ){//如果有开启可购买筛选 
            for(var i=0;i<allFunds.length;i++){
              if( parseInt(allFunds[i].fundstate) == 1 || parseInt(allFunds[i].fundstate) == 0  || parseInt(allFunds[i].fundstate) == 6){//允许购买push添加进去
                  currentFunds.push(allFunds[i]);
              }
            }
        }else{
                currentFunds = allFunds;
        }
    }
    return currentFunds;
}

function classifyEstimateFunds(currentType, searchTxt, data) {
    datatype = currentType;
    currentEstimateFunds = [];
    if (currentType == -2) {//如果是-2则点击的是我的关注
        orderMyEstimateFunds();
        //单独出来对我关注的基金先进行排序
        currentEstimateFunds = myEstimateFunds;

    } else if (currentType != -1 || searchTxt != "") {
        for (var i = 0; i < data.length; i++) {
            if (currentType == -1 || data[i].investmentstyle == currentType) {
                if (searchTxt != "") {
                    if (data[i].fundname.indexOf(searchTxt.toUpperCase()) < 0 && data[i].fundcode.indexOf(searchTxt) < 0 && data[i].backfundcode.indexOf(searchTxt) < 0) {
                        continue;
                    }
                }
                currentEstimateFunds.push(data[i]);
            }
        }
    } else {
        currentEstimateFunds = data;
    }
    return currentEstimateFunds;
}

var currentOrderBy = -1;
var currentEstimateOrderBy = -1;
// -1:逆序(默认)，1：升序，用于标示日涨跌、近半年等
var valOrderBy = -1;
var estimateValOrderBy = -1;
//用于标示单位净值和万份收益的的排序标示
var currentOrder = 1;
var currentEstimateOrder = 1;
//0:单位净值,1:涨跌  ,2:近半年  ,3:近一年 ,4:今年以来
//我关注的基金也进行排序
function orderMyFunds(num, flag) {
    if (flag) {
        var currentOrderBy = parseInt(valOrderBy);
    } else {//这里使用全局全局变量的currentOrderBy
        var currentOrderBy = window.currentOrderBy;
    }
    try {
        myFunds.sort(function(_a, _b) {
            if (_a.fundstate == 1 || (_a.topFlag == true && _a.fundstate == 0)) {
                return -1;
            }
            if (_b.fundstate == 1 || (_b.topFlag == true && _b.fundstate == 0)) {
                return 1;
            }

            if (currentOrder == 0) {//单位净值
                var _al = (isCurrency(_a.investmentstyle) ? _a.hf_incomeratio : _a.pernetvalue);
                var _bl = (isCurrency(_b.investmentstyle) ? _b.hf_incomeratio : _b.pernetvalue);
                return (parseFloat(_al) > parseFloat(_bl)) ? currentOrderBy : (0 - currentOrderBy);
            } else if (currentOrder == 1) {//涨跌
                var _al = (isCurrency(_a.investmentstyle) ? _a.incomeratio : _a.income);
                var _bl = (isCurrency(_b.investmentstyle) ? _b.incomeratio : _b.income);
                //var _al = (isCurrency(_a.investmentstyle)?0:_a.income);
                //var _bl = (isCurrency(_b.investmentstyle)?0:_b.income);
                return (parseFloat(_al) > parseFloat(_bl)) ? currentOrderBy : (0 - currentOrderBy);
            } else if (currentOrder == 2) {//近半年
                return (parseFloat(_a.recenthalfyear) > parseFloat(_b.recenthalfyear)) ? currentOrderBy : (0 - currentOrderBy);
            } else if (currentOrder == 3) {//近一年
                return (parseFloat(_a.recentoneyear) > parseFloat(_b.recentoneyear)) ? currentOrderBy : (0 - currentOrderBy);
            } else if (currentOrder == 4) {//今年以来
                return (parseFloat(_a.thisyear) > parseFloat(_b.thisyear)) ? currentOrderBy : (0 - currentOrderBy);
            }
        });
    } catch(e) {
    }
}

var allFunds = '';
//用于保存所有基金

// 基金排序-1:单位净值,2:涨跌  ,3:近半年  ,4:近一年 ,5:今年以来
function orderAllFunds(num, flag) {
    if (flag) {
        var currentOrderBy = parseInt(valOrderBy);
    } else {//这里使用全局全局变量的currentOrderBy
        var currentOrderBy = window.currentOrderBy;
    }
    try {
        allFunds.sort(function(_a, _b) {
            if (_a.fundstate == 1 || (_a.topFlag == true && _a.fundstate == 0)) {
                return -1;
            }
            if (_b.fundstate == 1 || (_b.topFlag == true && _b.fundstate == 0)) {
                return 1;
            }

            if (currentOrder == 0) {//单位净值或者是万份收益
                var _al = (isCurrency(_a.investmentstyle) ? _a.hf_incomeratio : _a.pernetvalue);
                var _bl = (isCurrency(_b.investmentstyle) ? _b.hf_incomeratio : _b.pernetvalue);
                return (parseFloat(_al) > parseFloat(_bl)) ? currentOrderBy : (0 - currentOrderBy);
            } else if (currentOrder == 1) {//涨跌
                var _al = (isCurrency(_a.investmentstyle) ? _a.incomeratio : _a.income);
                var _bl = (isCurrency(_b.investmentstyle) ? _b.incomeratio : _b.income);
                //var _al = (isCurrency(_a.investmentstyle)?0:_a.income);
                //var _bl = (isCurrency(_b.investmentstyle)?0:_b.income);
                return (parseFloat(_al) > parseFloat(_bl)) ? currentOrderBy : (0 - currentOrderBy);
            } else if (currentOrder == 2) {//近半年
                return (parseFloat(_a.recenthalfyear) > parseFloat(_b.recenthalfyear)) ? currentOrderBy : (0 - currentOrderBy);
            } else if (currentOrder == 3) {//近一年
                return (parseFloat(_a.recentoneyear) > parseFloat(_b.recentoneyear)) ? currentOrderBy : (0 - currentOrderBy);
            } else if (currentOrder == 4) {//今年以来
                return (parseFloat(_a.thisyear) > parseFloat(_b.thisyear)) ? currentOrderBy : (0 - currentOrderBy);
            }
        });
        orderMyFunds(num, flag);
    } catch(e) {
    }

    //对获取的估算净值基金进行排序
    if (flag) {
        var currentEstimateOrderBy = parseInt(estimateValOrderBy);
    } else {//这里使用全局全局变量的currentOrderBy
        var currentEstimateOrderBy = window.currentEstimateOrderBy;
    }
    try {
        estimateFunds.sort(function(_a, _b) {
            if (_a.fundstate == 1 || (_a.topFlag == true && _a.fundstate == 0)) {
                return -1;
            }
            if (_b.fundstate == 1 || (_b.topFlag == true && _b.fundstate == 0)) {
                return 1;
            }

            if (currentEstimateOrder == 0) {//估算净值
                return (parseFloat(_a.new_nav) > parseFloat(_b.new_nav)) ? currentEstimateOrderBy : (0 - currentEstimateOrderBy);
            } else if (currentEstimateOrder == 1) {//估算涨跌
                return (parseFloat(_a.new_rate) > parseFloat(_b.new_rate)) ? currentEstimateOrderBy : (0 - currentEstimateOrderBy);
            }
        });
        orderMyEstimateFunds(num, flag);
    } catch(e) {
    }
}

//我关注的基金也进行排序
function orderMyEstimateFunds(num, flag) {
    if (flag) {
        var currentEstimateOrderBy = parseInt(estimateValOrderBy);
    } else {//这里使用全局全局变量的currentOrderBy
        var currentEstimateOrderBy = window.currentEstimateOrderBy;
    }
    try {
        myEstimateFunds.sort(function(_a, _b) {
            if (_a.fundstate == 1 || (_a.topFlag == true && _a.fundstate == 0)) {
                return -1;
            }
            if (_b.fundstate == 1 || (_b.topFlag == true && _b.fundstate == 0)) {
                return 1;
            }
            if (currentEstimateOrder == 0) {//净值估算
                return (parseFloat(_a.new_nav) > parseFloat(_b.new_nav)) ? currentEstimateOrderBy : (0 - currentEstimateOrderBy);
            } else if (currentEstimateOrder == 1) {//估值涨跌
                return (parseFloat(_a.new_rate) > parseFloat(_b.new_rate)) ? currentEstimateOrderBy : (0 - currentEstimateOrderBy);
            }
        });
    } catch(e) {
    }
}

var showTitle = '';
//弹出层点击事件
function itemClick(num) {
    toggleChoose();
    if (event != undefined) {
        event.stopPropagation();
    }
    var selTextObj = $('.selText');
    var inputObj = $('.cover input')[num];
    currentInscTab = ($(inputObj).data('type') - 1);
    currentOrder = $(inputObj).data('type');
    //alert(inputObj.checked);
    if (!inputObj.checked) {
        $('.icon-down').removeClass('uhide');
        $('.icon-up').addClass('uhide');
        inputObj.checked = true;
        currentOrderBy = -1;
        // -1:逆序(默认)，1：升序
        fundsOrderChange($(inputObj).data('type'));
        //讲升降图标改为默认图标
        $('#orderBtn2').removeClass('btn-select-up').addClass('btn-select-down');
    } else if (inputObj.checked) {//如果在选中的情况下仍然进行点击,则进行排序
        currentOrderBy = 0 - currentOrderBy;
        // -1:逆序(默认)，1：升序
        fundsOrderChange($(inputObj).data('type'));
        if (currentOrderBy != -1) {
            $('.icon-down').addClass('uhide');
            $('.icon-up').removeClass('uhide');
            $('#orderBtn2').removeClass('btn-select-down').addClass('btn-select-up');
        } else {
            $('.icon-down').removeClass('uhide');
            $('.icon-up').addClass('uhide');
            $('#orderBtn2').removeClass('btn-select-up').addClass('btn-select-down');
        }
    }
    closeSortShow();
    showTitle = selTextObj.eq(num).text().trim();
    $('.js-val-1').html(showTitle);

    $('#orderBtn1').removeClass('btn-select-down').removeClass('btn-select-up')
    return false;
}

//全部基金排序
function fundsOrderChange(num, flag) {
    currentOrder = num;
    //0:单位净值,1:涨跌  ,2:近半年  ,3:近一年 ,4:今年以来
    orderAllFunds(num, flag);
    var res = classifyFunds(currentType, "", allFunds,subtype);
    $('#list-funds').html((_.template(myTemp))({
        list : res,
        currentInscTab : currentInscTab
    }));
    //按类别显示
    document.body.scrollTop = 0;
}

//估算基金排序
function estimateOrderChange(num, flag) {
    currentEstimateOrder = num;
    orderAllFunds(num, flag);
    res = classifyEstimateFunds(currentType, "", estimateFunds);
    $('#estimate-list-funds').html((_.template(estimateTemp))({
        list : res
    }));
    //按类别显示
    document.body.scrollTop = 0;
}

var sortShowFinish = true;
function closeSortShow() {
    if (event != undefined) {
        event.stopPropagation();
    }
    sortShowFinish = false;
    try {
        closeCover();
        $('.arrow_con').addClass('uhide');
        $('div.icon').removeClass('icon_downup_ani').addClass('icon_updown_ani');
        setTimeout(function() {
            sortShowFinish = true;
        }, 500);
    } catch(e) {
        sortShowFinish = true;
    }
    return false;
}

function closeCover() {
    var coverObj = $('.cover');
    coverObj.addClass('uhide');
    return false;
}

//切换选择层的显示和隐藏
function toggleChoose(flag) {
    if (!$('.arrow_con').hasClass('uhide') || flag) {
        $('.mask-select').addClass('uhide');
        $('.arrow_con').addClass('uhide');
        $('div.icon').removeClass('icon_downup_ani').addClass('icon_updown_ani');
    } else {
        $('.mask-select').removeClass('uhide');
        $('.arrow_con').removeClass('uhide');
        $('div.icon').removeClass('icon_updown_ani').addClass('icon_downup_ani');
    }
}

//单独对净值进行排序
function orderVal(num) {
    valOrderBy = num;
    fundsOrderChange(0, true);
    //0表示单位净值
}

//单独对估算净值进行排序
function orderEstimateFunds(flag, num) {
    estimateValOrderBy = num;
    estimateOrderChange(flag, true);
    //0表示单位净值
}

function orderFunds(data, currentOrder) {//基金排序
    data.sort(function(_a, _b) {

        if (_a.fundstate == 1 || (_a.topFlag == true && _a.fundstate == 0)) {
            return -1;
        }
        if (_b.fundstate == 1 || (_b.topFlag == true && _b.fundstate == 0)) {
            return 1;
        }
        if (currentOrder == 0) {//按单位净值
            var _al = (isCurrency(_a.investmentstyle) ? _a.hf_incomeratio : _a.pernetvalue);
            var _bl = (isCurrency(_b.investmentstyle) ? _b.hf_incomeratio : _b.pernetvalue);
            return (parseFloat(_al) < parseFloat(_bl)) ? currentOrderBy : (0 - currentOrderBy);
        } else if (currentOrder == 1) {//按涨跌
            var _al = (isCurrency(_a.investmentstyle) ? _a.incomeratio : _a.income);
            var _bl = (isCurrency(_b.investmentstyle) ? _b.incomeratio : _b.income);
            return (parseFloat(_al) < parseFloat(_bl)) ? currentOrderBy : (0 - currentOrderBy);
        } else if (currentOrder == 2) {//按近半年
            return (parseFloat(_a.recenthalfyear) < parseFloat(_b.recenthalfyear)) ? currentOrderBy : (0 - currentOrderBy);
        } else if (currentOrder == 3) {//按近一年
            return (parseFloat(_a.recentoneyear) < parseFloat(_b.recentoneyear)) ? currentOrderBy : (0 - currentOrderBy);
        } else if (currentOrder == 4) {//按今年以来
            return (parseFloat(_a.thisyear) < parseFloat(_b.thisyear)) ? currentOrderBy : (0 - currentOrderBy);
        }
    });
    return data;
}

function openHotFundDetail(num, flag) {
    var fundDetail = hotFunds[num];
    setLocVal('fundDetail', JSON.stringify(fundDetail));
    if (fundDetail.fundcode === superXjbCode) {
        location.href = 'xjbDetail.html';
        return;
    }
    var param = {
        fundcode : fundDetail.fundcode,
        fundname : fundDetail.fundname,
        fundtype : fundDetail.fundtype,
        fundstate : fundDetail.fundstate,
        fixFundFlag : fundDetail.fixFundFlag,
         fundrisklevel: fundDetail.fundrisklevel,
         spflag:fundDetail.spflag
    }
    location.href = "fundDetail.html?v=20180614&" + paramSerialize(param)
}

function isCurrency(investmentstyle) {
    return investmentstyle == "7" || investmentstyle == "8";
}

//最上面菜单切换
function tabClick(index, navCurrent) {
    currentType = null;//重置currentType
    sessionStorage.setItem("fundtab", index);
    if (!$('#tab' + index).hasClass('btn-colorblue')) {
        $(window).scrollTop(0);
        if (index == 0) {
              $('#moneyClass').parent().addClass('uhide');
               $('#expClass').parent().addClass('uhide');
            $('#tab0').addClass('btn-colorblue');
            $('#tab1').removeClass('btn-colorblue');
            $('#tab2').removeClass('btn-colorblue');
            $('#commonList').addClass('uhide');
            $('#totalList').addClass('uhide');
            $('#hot-list-funds').removeClass('uhide');
            $('#estimateList').addClass('uhide');
            if(sessionStorage.getItem("fundPiwikLock")!=1){
                sessionStorage.setItem("fundPiwikLock",1);
                piwikTrackEvent(Piwik_Event_Quota.fund.category,Piwik_Event_Quota.fund.hot_fund_tab.action,"");
                setTimeout(function() {
                    sessionStorage.setItem("fundPiwikLock",0);
                }, 300);                        
            }   
            $('#filterBtn').addClass('uhide');  
            $('.js-filterCon').addClass('uhide');           
        } else if (index == 1) {
            $('#tab0').removeClass('btn-colorblue');
            $('#tab1').addClass('btn-colorblue');
            $('#tab2').removeClass('btn-colorblue');

            $('#commonList').removeClass('uhide');
            $('#totalList').removeClass('uhide');
            $('#hot-list-funds').addClass('uhide');
            $('#estimateList').addClass('uhide');
            if (navCurrent != undefined) {//点击我的关注相关处理
                initTitle('all', navCurrent);
                var res = classifyFunds('-2', $.trim($('#search-condition').val()), allFunds);
                $('#list-funds').html((_.template(myTemp))({
                    list : res
                }));
                //更新list-funds
                currentType = -2;
            } else {
                initTitle('all');
                totalTabClick( $('.js-total-tab').eq(0) );
                // $('#list-funds').html((_.template(myTemp))({
                    // list : allFunds,
                    // currentInscTab : currentInscTab
                // }));
                if(sessionStorage.getItem("fundPiwikLock")!=1){
                    sessionStorage.setItem("fundPiwikLock",1);
                    piwikTrackEvent(Piwik_Event_Quota.fund.category,Piwik_Event_Quota.fund.all_fund_tab.action,"");
                    setTimeout(function() {
                        sessionStorage.setItem("fundPiwikLock",0);
                    }, 300);                        
                }                 
            }
             $('#filterBtn').removeClass('uhide');  
        } else if (index == 2) {
             $('#moneyClass').parent().addClass('uhide');
               $('#expClass').parent().addClass('uhide');
            if (getLocVal('hasShowEstimate')) {
                agreeEst();
            } else {
                var conStr = '<p style="line-height:1.5em;">实时净值估算在每个交易日的9:30-15:00盘中实时更新，估算的实时净值是根据过往公开数据的相关性分析统计而出，并不对应基金的实际净值，也不代表投资者的实际交易价格，本公司不对旗下基金的实际净值做出任何承诺或暗示，投资者据此进行基金交易的责任自负、风险自担。基金申购赎回严格遵循未知价原则，投资者如需查阅基金实际净值敬请关注收市后的净值披露信息。净值估算数据来源于东方财富信息股份有限公司，仅供参考。</p>';
                dialogConfirm(conStr, '', agreeEst, '', '<div>同意</div>', '<div style="color:black;">不同意</div>');
            }
            if(sessionStorage.getItem("fundPiwikLock")!=1){
                sessionStorage.setItem("fundPiwikLock",1);
                piwikTrackEvent(Piwik_Event_Quota.fund.category,Piwik_Event_Quota.fund.est_fund_tab.action,"");
                setTimeout(function() {
                    sessionStorage.setItem("fundPiwikLock",0);
                }, 300);                        
            }      
             $('#filterBtn').addClass('uhide');   
             $('.js-filterCon').addClass('uhide');       
        }
       // getCouponData();
    }
}

//同意挂算弹框
function agreeEst() {
    setLocVal('hasShowEstimate', true);
    $('#tab0').removeClass('btn-colorblue');
    $('#tab1').removeClass('btn-colorblue');
    $('#tab2').addClass('btn-colorblue');

    $('#commonList').removeClass('uhide');
    $('#totalList').addClass('uhide');
    $('#hot-list-funds').addClass('uhide');
    $('#estimateList').removeClass('uhide');
    initTitle();
    estTabClick( $('.js-est-tab').eq(0) );
    // $('#estimate-list-funds').html((_.template(estimateTemp))({
        // list : estimateFunds
    // }));

}

function btn1Click() {
    toggleChoose(true);
    //对弹出层的切换
    $('#orderBtn2').removeClass('btn-select-down').removeClass('btn-select-up');
    if ($('#orderBtn1').hasClass('btn-select-down')) {
        $('#orderBtn1').removeClass('btn-select-down').addClass('btn-select-up');
        orderVal(1)
    } else {
        $('#orderBtn1').removeClass('btn-select-up').addClass('btn-select-down');
        orderVal(-1)
    }
}

function orderEstimateVal() {
    $('#orderEstimateRate').removeClass('btn-select-down').removeClass('btn-select-up');
    if ($('#orderEstimateVal').hasClass('btn-select-down')) {
        $('#orderEstimateVal').removeClass('btn-select-down').addClass('btn-select-up');
        orderEstimateFunds(0, 1);
    } else {
        $('#orderEstimateVal').removeClass('btn-select-up').addClass('btn-select-down');
        orderEstimateFunds(0, -1)
    }
}

function orderEstimateRate() {
    $('#orderEstimateVal').removeClass('btn-select-down').removeClass('btn-select-up');
    if ($('#orderEstimateRate').hasClass('btn-select-down')) {
        $('#orderEstimateRate').removeClass('btn-select-down').addClass('btn-select-up');
        orderEstimateFunds(1, 1);
    } else {
        $('#orderEstimateRate').removeClass('btn-select-up').addClass('btn-select-down');
        orderEstimateFunds(1, -1)
    }
}

function initTitle(type, navCurrent) {
    $('#menu').html('');
    var str = '';
    if (type == 'all') {
        var tabList = [{
            name : "全部",
            dataType : "-1",
            dataIndex : "0",
            titleType : "0"
        }, {
            name : "我的关注",
            dataType : "-2",
            dataIndex : "-2",
            titleType : "0"
        }, {
            name : "货币型",
            dataType : "7",
            dataIndex : "6",
            titleType : "0",
            init:true
        }, {
            name : "股票型",
            dataType : "0",
            dataIndex : "3",
            titleType : "0"
        }, {
            name : "混合型",
            dataType : "1",
            dataIndex : "4",
            titleType : "0"
        }, {
            name : "保本型",
            dataType : "5",
            dataIndex : "5",
            titleType : "0"
        }, {
            name : "指数型",
            dataType : "6",
            dataIndex : "7",
            titleType : "0",
             init:true
        }, {
            name : "债券型",
            dataType : "3",
            dataIndex : "1",
            titleType : "0"
        }, {
            name : "QDII",
            dataType : "99",
            dataIndex : "8",
            titleType : "0"
        }, {
            name : "FOF",
            dataType : "9",
            dataIndex : "9",
            titleType : "0"
        }, {
            name : "理财型",
            dataType : "8",
            dataIndex : "2",
            titleType : "0"
        }];

        if (navCurrent != undefined) {
            for (var i = 0; i < tabList.length; i++) {
                if (i == navCurrent) {
                    str += '<div class="wmz-tab-slide nav_current js-total-tab"  data-init="'+( tabList[i].init?tabList[i].init:'')+'" data-type="' + tabList[i].dataType + '" data-index="' + tabList[i].dataIndex + '" data-titleType="' + tabList[i].titleType + '"  >' + tabList[i].name + '</div>';
                } else {
                    str += '<div class="wmz-tab-slide js-total-tab"  data-init="'+( tabList[i].init?tabList[i].init:'')+'" data-type="' + tabList[i].dataType + '" data-index="' + tabList[i].dataIndex + '"   data-titleType="' + tabList[i].titleType + '"  >' + tabList[i].name + '</div>';
                }
            }
        } else {
            for (var i = 0; i < tabList.length; i++) {
                if (i == 0) {
                    str += '<div class="wmz-tab-slide nav_current js-total-tab"  data-init="'+( tabList[i].init?tabList[i].init:'')+'" data-type="' + tabList[i].dataType + '" data-index="' + tabList[i].dataIndex + '" data-titleType="' + tabList[i].titleType + '"  >' + tabList[i].name + '</div>';
                } else {
                    str += '<div class="wmz-tab-slide js-total-tab"  data-init="'+( tabList[i].init?tabList[i].init:'')+'" data-type="' + tabList[i].dataType + '" data-index="' + tabList[i].dataIndex + '"   data-titleType="' + tabList[i].titleType + '"  >' + tabList[i].name + '</div>';
                }
            }
        }

    } else {
        var tabList = [{
            name : "全部",
            dataType : "-1",
            dataIndex : "0",
            titleType : "1"
        }, {
            name : "我的关注",
            dataType : "-2",
            dataIndex : "-2",
            titleType : "1"
        }, {
            name : "股票型",
            dataType : "0",
            dataIndex : "3",
            titleType : "1"
        }, {
            name : "混合型",
            dataType : "1",
            dataIndex : "4",
            titleType : "1"
        }, {
            name : "保本型",
            dataType : "5",
            dataIndex : "5",
            titleType : "1"
        }, {
            name : "指数型",
            dataType : "6",
            dataIndex : "7",
            titleType : "1"
        }];
        for (var i = 0; i < tabList.length; i++) {
            if (i == 0) {
                str += '<div class="wmz-tab-slide nav_current js-est-tab" data-type="' + tabList[i].dataType + '" data-index="' + tabList[i].dataIndex + '" data-titleType="' + tabList[i].titleType + '"  >' + tabList[i].name + '</div>';
            } else {
                str += '<div class="wmz-tab-slide js-est-tab" data-type="' + tabList[i].dataType + '" data-index="' + tabList[i].dataIndex + '"   data-titleType="' + tabList[i].titleType + '"  >' + tabList[i].name + '</div>';
            }
        }
    }
    $('#menu').html(str);
    iScroll.prototype.refresh();
    // A.launch({
    // showPageLoading : false,
    // isAutoRender : true,
    // crossDomainHandler : $util.ajax
    // });
}

function selectMyEstimateFunds() {
    myEstimateFunds = [];
    //myEstimateFunds.push(currentEstimateFunds[i]);
    for (var j = 0; j < estimateFunds.length; j++) {
        for (var i = 0; i < myFunds.length; i++) {
            if (myFunds[i].fundcode == estimateFunds[j].fundcode) {
                myEstimateFunds.push(estimateFunds[j]);
            }
        }
    }
}


